# encoding: utf-8
import random
import string

#Image: 一个画布
#ImageDraw: 一个画笔
#ImageFont: 画笔的字体
from PIL import Image, ImageDraw, ImageFont

class Captcha(object):
    number = 6         #生成验证码的位数
    size = (200, 60)   #生成验证码的宽和高
    fontSize = 56      #验证码字体的大小
    line_number = 2    #干扰线的数量

    source = list(string.ascii_letters)  #构建验证码的源
    for index in range(0, 10):
        source.append(str(index))

    # 生成图片验证码
    @classmethod
    def generate_graph_captcha(cls):
        # 获取图形验证码的宽和高
        width, height = cls.size

        # 创建图片
        image = Image.new("RGBA", (width, height), cls._generate_random_color(200, 255))

        # 验证码的字体
        font = ImageFont.truetype(cls._generate_random_font(), cls.fontSize)

        # 创建画笔
        draw = ImageDraw.Draw(image)

        # 生成字符串
        text = cls.generate_random_text(6)

        # 获取字体的尺寸
        font_width, font_height = font.getsize(text)

        # 填充字体符合
        print(cls._generate_random_color(155, 255))
        draw.text(((width - font_width ) / 2, (height - font_height) / 2), text, font=font, fill=cls._generate_random_color(0, 100))

        # 绘制干扰线
        for x in range(0, cls.line_number):
            cls._draw_line(draw, width, height)

        # 绘制噪点
        cls._draw_points(draw, 10, width, height)

        with open("1.png", "wb") as f:
            image.save(f)

        return (text, image)

    @classmethod
    def _generate_random_color(cls, start=0, end=255):
        random.seed()
        return (random.randint(start, end), random.randint(start, end), random.randint(start, end))

    @classmethod
    def _generate_random_font(cls):
        fonts = [
            "Hootie.ttf",
            "Michaelmas.ttf"
        ]
        font = random.choice(fonts)
        return "utils/captcha/{0}".format(font)

    @classmethod
    def generate_random_text(cls, number):
        return "".join(random.sample(cls.source, 6))

    @classmethod
    def _draw_line(cls, draw, width, height):
        begin = (random.randint(0, width), random.randint(0, height))
        end = (random.randint(0, width), random.randint(0, height))

        draw.line([begin, end], fill=cls._generate_random_color(), width=2)

    @classmethod
    def _draw_points(cls, draw, point_chance, width, height):
        chance = min(100, max(0, int(point_chance))) # 大小限制在0～100之间
        for w in range(width):
            for h in range(height):
                tmp = random.randint(0, 100)
                if tmp > 100 - chance:
                    draw.point((w,h), fill=cls._generate_random_color())
